<!-- 供应商管理-供应商初选列表  -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <a-dropdown @select="inviteSelect">
        <a-button
          :style="{
            backgroundColor: '#31C27C',
            color: '#fff',
          }"
        >
          <template #icon>
            <icon-plus />
          </template>
          <template #default>邀请供应商</template>
        </a-button>
        <template #content>
          <a-doption :value="1">生成二维码</a-doption>
          <a-doption :value="2">生成邀请链接</a-doption>
        </template>
      </a-dropdown>
      <a-dropdown @select="add">
        <a-button type="primary">
          <template #icon>
            <icon-plus />
          </template>
          <template #default>添加供应商</template>
        </a-button>
        <template #content>
          <a-doption
            v-for="item in levelList.list"
            :key="item.id"
            :value="item.id"
            >{{ `${item.name}供应商` }}
          </a-doption>
        </template>
      </a-dropdown>
    </template>
  </pageHeader>
  <!-- <a-space class="client-list-header"> -->
  <div class="search-box">
    <div>
      <a-space>
        <div>
          <a-input-group>
            <a-select
              :style="{ width: '120px' }"
              placeholder="请选择"
              v-model="currSelectVal"
            >
              <a-option value="number">供应商编号</a-option>
              <a-option value="name">供应商名称</a-option>
            </a-select>
            <a-input-search
              :style="{ width: 'auto' }"
              placeholder="请输入"
              v-model="currSelectSearch"
              @search="search"
              search-button
            />
          </a-input-group>
        </div>
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>

    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>
        <a-button status="warning">
          <template #icon>
            <icon-export rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>
        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <!-- </a-space> -->
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableTurnRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        :title="item.name"
        v-for="(item, index) in selectedHeader"
        :key="index"
        :data-index="item.code"
        align="center"
        :width="150"
        :ellipsis="true"
        :tooltip="{
          position: 'top',
        }"
      >
        <template v-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
        </template>
        <template v-else-if="item.code === 'state'" #cell="{ record }">
          <div class="state">
            <div
              class="state-box"
              :class="
                record.state == 1
                  ? 'WaitSubmitted'
                  : record.state == 2
                  ? 'Examining'
                  : record.state == 3
                  ? 'Examining'
                  : record.state == 4
                  ? 'Pass'
                  : record.state == 5
                  ? 'NoPass'
                  : 'Pass'
              "
            >
              {{
                record.state == 1
                  ? '待提交'
                  : record.state == 2
                  ? '待审核'
                  : record.state == 3
                  ? '审核中'
                  : record.state == 4
                  ? '通过'
                  : record.state == 5
                  ? '不通过'
                  : '合格'
              }}
            </div>
          </div>
        </template>
      </a-table-column>
      <!-- <a-table-column
        :title="item.name"
        v-for="(item, index) in StateHead"
        :key="index"
        :data-index="item.code"
        align="center"
        :width="200"
      >

      </a-table-column> -->

      <!-- 操作item -->
      <a-table-column align="center" :width="150" fixed="right" title="操作">
        <template #cell="{ record }">
          <!-- <a-button
            
            type="text"
            :style="{
              backgroundColor: '#31C27C',
              color: '#fff',
            }"
            
            >提交</a-button
          > -->

          <a-tooltip v-if="record.state === 1" content="提交审核">
            <IconFont
              type="icon-tijiaoshenhe1"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="Submit(record)"
            />
          </a-tooltip>

          <a-tooltip v-if="record.state === 1" content="进入详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goEdit(record)"
            />
          </a-tooltip>

          <a-tooltip v-if="record.state !== 1" content="查看详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDetail(record)"
            />
          </a-tooltip>

          <a-tooltip content="删除">
            <a-popconfirm
              content="确认删除？"
              type="error"
              @ok="del(record.id)"
            >
              <IconFont
                type="icon-delete"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
              />
            </a-popconfirm>
          </a-tooltip>
          <!-- <a-button
            v-if="record.state !== 1"
            type="text"
            @click="goDetail(record)"
            >查看详情</a-button
          > -->
          <!-- <a-popconfirm
            @ok="deleteItem(record.id)"
            content="确定删除吗"
            type="error"
          >
            <a-button
              v-if="record.state === 1"
              type="text"
              :style="{
                color: 'red',
              }"
              >删除</a-button
            > -->
          <!-- <a-button v-if="record.state === 3" type="text">发送通知</a-button> -->
          <!-- <a-button v-if="record.state === 4" type="text">发送通知</a-button> -->
          <!-- <a-button
              disabled
              v-if="record.state === 4"
              type="text"
              :style="{
                color: 'grey',
              }"
              >已发通知</a-button
            > -->
          <!-- </a-popconfirm> -->
        </template>
      </a-table-column>
    </tableTurn>
  </div>

  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="供应商初选列表表头设置"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
    :forbidList="forbidList"
  ></FormHeaderSetting>

  <invitationModal
    v-model:visible="inviteModal"
    :flag="inviteFlag"
  ></invitationModal>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, watchEffect, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import { GetSupplierLevelInfo } from '@/api/buy-management/supplier-management/base-setting';
  import {
    GetSupplierPrimaryList,
    DelSupplierPrimaryList,
    GetSupplierPrimaryHeaderList,
    PutSupplierPrimaryHeaderList,
    putSupplierPrimaryDetail,
    setSupplierState,
  } from '@/api/buy-management/supplier-management/supplier-primary-list';
  import cloneDeep from 'lodash.clonedeep';
  import dayjs from 'dayjs';
  import { formHeaderSetting } from '@/types/global';
  import invitationModal from './components/invitation-modal/index.vue';

  const router = useRouter();
  const title = '供应商初选列表';
  const breadCrumb = ['采购管理', '供应商管理', '供应商初选列表'];

  const headerSetting = reactive<formHeaderSetting>({
    list: [],
  });

  const forbidList = reactive(['salesName']); // 禁止移动的表头， (销售员)

  // 表格配置
  const args = reactive({
    stripe: true,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
    scroll: {
      y: 500,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });
  let tableTurnRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  let currNameSearch = ref(''); // 储存搜索供应商名称的值
  let isFirstSelect = ref(true); // 判断是否是第一次进入页面

  // 供应商列表状态
  const supplierListState = reactive<any>({
    list: [],
  });

  // 获取列表数据
  const getData = async (pageData?: any) => {
    try {
      const res = await GetSupplierPrimaryList({
        ...pageData,
        name: isFirstSelect.value ? undefined : currNameSearch.value,
        [currSelectVal.value]: isFirstSelect.value
          ? undefined
          : currSelectSearch.value,
      });
      isFirstSelect.value = false;
      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let levelList = reactive<any>({
    list: [],
  });

  const getLevelData = async () => {
    try {
      const { data } = await GetSupplierLevelInfo();
      levelList.list = data;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getLevelData();

  // 搜索按钮
  const search = () => {
    tableTurnRef.value.refreshPaging();
    tableTurnRef.value.loadData();
  };
  // 重置按钮
  const reset = () => {
    currSelectSearch.value = '';
    currNameSearch.value = '';
    currSelectVal.value = '';
    tableTurnRef.value.refreshPaging();
    tableTurnRef.value.loadData();
  };

  // 获取表头设置列表
  const getHeaders = async () => {
    try {
      const tableHead = await GetSupplierPrimaryHeaderList({
        supplierType: 1,
        userId: 2,
      });
      headerSetting.list = tableHead.extends;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  getHeaders();

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: formHeaderSetting['list'] = [];
    headerSetting.list.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  // 储存客户人员信息
  const clientList = reactive([]);

  // 点击新增供应商
  const add = (id: number) => {
    router.push({
      name: 'SupplierPrimarySelectionListAdd',
      query: {
        type: 'add',
        supLevelId: id,
      },
    });
  };

  let formHeaderSettingVisible = ref<boolean>(false); // 是否显示表头设置组件

  // 表头设置按钮
  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  // 表头设置保存后返回的自定义事件
  const headerSave = async (headerList: formHeaderSetting['list']) => {
    try {
      const data = {
        userId: 2,
        supplierType: 1,
        extend: JSON.stringify(headerList),
      };
      await PutSupplierPrimaryHeaderList(data);
      headerSetting.list = [...headerList];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  let inviteModal = ref(false); // 判断邀请链接对话框是否显示
  let inviteFlag = ref(1); // 判断是二维码邀请还是链接邀请

  const inviteSelect = (val: number) => {
    inviteFlag.value = val;
    inviteModal.value = true;
  };

  let currId = ref(-1); // 储存当前选中的id

  // 去往对应的编辑页面
  const goEdit = (record: any) => {
    router.push({
      name: 'SupplierPrimarySelectionListAdd',
      query: {
        supplierId: record.id,
        templateId: record.templateId,
        supLevelId: record.supLevelId,
        type: 'edit',
      },
    });
  };

  // 去往对应的详情页面
  const goDetail = (record: any) => {
    router.push({
      name: 'SupplierPrimarySelectionListAdd',
      query: {
        supplierId: record.id,
        templateId: record.templateId,
        supLevelId: record.supLevelId,
        type: 'detail',
      },
    });
  };

  const Submit = async ({ id }) => {
    try {
      await setSupplierState({ id, state: 2 });
      tableTurnRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };

  // 删除一项
  const deleteItem = async (id: number) => {
    try {
      await DelSupplierPrimaryList({
        id,
      });
      tableTurnRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
    margin-top: -7px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }

  .state {
    text-align: center;
    display: flex;
    justify-content: center;
    &-box {
      width: 50px;
      border-radius: 15px;
      line-height: 26px;
      color: #fff;
      height: 26px;
    }
    .WaitSubmitted {
      // 待提交
      background: #c9cdd4;
    }
    .Examining {
      // 审核中
      background: #165dff;
    }
    .Pass {
      // 已通过
      background: #31c27c;
    }
    .NoPass {
      //不通过
      background: #f53f3f;
    }
    .Qualified {
      // 合格
      background: #ff9a2e;
    }
  }
</style>
